package com.rocksea.app.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;

import com.mor.dataacquisition.DataAcquisition;
import com.mor.dataacquisition.net.DataCallBack;
import com.mor.dataacquisition.net.parsedData.ResponseForLogin;
import com.rocksea.app.Account;
import com.rocksea.app.R;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.entry.CheckVersion;
import com.rocksea.app.http.UpDateTask;
import com.rocksea.app.service.DownloadService;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.utils.UiUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by 吴志华 on 2017/7/21.
 *
 */

public class LoginActivity extends BaseAppCompatActivity implements TextView.OnEditorActionListener, UpDateTask.CheckVersionCallBack {

    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案

    @InjectView(R.id.Login)
    Button mLogin;
    @InjectView(R.id.Pass_Word)
    AutoCompleteTextView mPssWord;
    @InjectView(R.id.User_Name)
    AutoCompleteTextView mUserName;
    @InjectView(R.id.initMessage)
    TextView initMessage;

    private ProgressDialog mDialog;
    private String account;
    private String pwd;

    @OnClick(R.id.Login)
    public void requestLogin(View view)
    {
        if (isInitOk)
            httpRequestLogin();
        else
            UiUtils.showToast("正在初始化,请稍后");
    }

    private String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_WIFI_STATE,
    };
    private static final int REQUEST_CODE = 0;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mUserName.requestFocus();
        mUserName.setText(PerUtils.getString(Account.ACCOUNT_KEY, ""));
        mPssWord.setText(PerUtils.getString(Account.PASSWORD_KEY, ""));
        mUserName.setOnEditorActionListener(this);
        mPssWord.setOnEditorActionListener(this);

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                requestPermission();
                return;
            }
        }
        // TODO 正式版再发布
        // UpDateTask.checkUpDate(this);
        init();
    }

    private void requestPermission()
    {
        ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PackageManager.PERMISSION_GRANTED:
                for (int grantResult : grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                        builder.setTitle("提示");
                        builder.setIcon(android.R.drawable.ic_dialog_alert);
                        builder.setMessage("权限不足，程序无法运行");
                        builder.setPositiveButton("去配置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                startAppSettings();
                            }
                        });
                        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                android.os.Process.killProcess(android.os.Process.myPid());
                                System.exit(1);
                            }
                        });
                        builder.show();
                        return;
                    }
                }
                init();
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void requrstAgin() {
    }

    @Override
    protected void initData() {
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE)
        {
            if (isInitOk)
                httpRequestLogin();
            else
                UiUtils.showToast("正在初始化,请稍后");
        }
        return false;
    }

    private void showDia() {
        mDialog = ProgressDialog.show(this, "提示", "正在登录中...");
    }

    private void dismiss() {
        if (mDialog != null)
            mDialog.dismiss();
    }

    private boolean verifFrom() {
        String userName = mUserName.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            mUserName.requestFocus();
            mUserName.setError("用户名不能为空");
            return false;
        }
        String password = mPssWord.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            mPssWord.requestFocus();
            mPssWord.setError("密码不能为空");
            return false;
        }
        return true;
    }

    private void httpRequestLogin()
    {
        if (!UiUtils.hasNet(this))
        {
            UiUtils.JumpActivity(LoginActivity.this, MainActivity.class);
            finish();
            return;
        }
        if (verifFrom()) {
            showDia();
            DataAcquisition dataAcquisition = new DataAcquisition();
            account = mUserName.getText().toString().trim();
            pwd = mPssWord.getText().toString().trim();
            dataAcquisition.verifyAppUser(account, "RS", pwd, "12345678", this, loginDataCallBack);
        }
    }

    private DataCallBack<ResponseForLogin> loginDataCallBack = new DataCallBack<ResponseForLogin>() {
        @Override
        public void processData(ResponseForLogin data) {
            super.processData(data);
            switch (data.returnCode)
            {
                case "-1":
                    mUserName.requestFocus();
                    mUserName.setError("用户名有误");
                    break;
                case "-3":
                    mPssWord.requestFocus();
                    mPssWord.setError("密码不正确");
                    break;
                case "-2":
                case "-4":
                case "-99":
                    UiUtils.showToast(String.format("未知错误(%s)", data.returnCode));
                    break;
                case "-90":
                    UiUtils.showToast("网络异常");
                    break;
                default:
                    UiUtils.showToast("登录成功");
                    Account.setRandomCode(data.returnCode);  //保存全局的随机码
                    Account.setAccount(account);             //保存用户名

                    PerUtils.setString(Account.RANDOM_CODE_KEY, data.returnCode);
                    PerUtils.setString(Account.ACCOUNT_KEY, account);
                    PerUtils.setString(Account.PASSWORD_KEY, pwd);
                    UiUtils.JumpActivity(LoginActivity.this, MainActivity.class);
                    finish();
                    break;
            }
            dismiss();
        }
    };

    public void init()
    {
        initMessage.setText("正在初始化...");
        EventBus.getDefault().post(new InitEvent());
    }

    private void startAppSettings()
    {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }

    private boolean isInitOk = false;

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onInitEvent(InitEvent event)
    {
        try
        {
            DbCenter.init(this);
        }
        catch (Exception e)
        {
            EventBus.getDefault().post(new InitOk(1));
            return;
        }
        EventBus.getDefault().post(new InitOk(0));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onInitEvent(InitOk event)
    {
        if (event.mode == 0)
        {
            initMessage.setTextColor(ContextCompat.getColor(this,R.color.colorPrimary));
            initMessage.setText("初始化成功!");
            isInitOk = true;
        }
        else
        {
            initMessage.setTextColor(ContextCompat.getColor(this,android.R.color.holo_red_dark));
            initMessage.setText("初始化失败!");
        }
    }

    @Override
    protected void onDestroy()
    {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onCheckVersionCallBack(final CheckVersion.DataBean.ListBean verInfo)
    {

        String versionName = UiUtils.getVersion();
        if (versionName == null || verInfo==null || versionName.equals(verInfo.getVersionName()))
        {
            UiUtils.showToast("已是最新版本");
            return;
        }
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setTitle("发现新版本");
        builder.setMessage(verInfo.getDescription());
        builder.setCancelable(false);
        builder.setPositiveButton("马上更新", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                Intent intent = new Intent(LoginActivity.this,DownloadService.class);
                intent.setData(Uri.parse(verInfo.getAppUrl()));
                startService(intent);
            }
        });
        builder.setNegativeButton("忽略", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    class InitEvent
    {
        public InitEvent(){}
    }

    class InitOk
    {
        public int mode = 0;
        public InitOk()
        {}

        public InitOk(int mode) {
            this.mode = mode;
        }
    }
}
